var flushPriceMax = 1; // 最大刷新价格次数

// 程序变量
var rdCheck; // 请求随机码
var totalAmount; // 现金支付金额
var cardAmount; // 礼品卡支付金额
var phoneNum;

// 刷新价格，使用余额
function flushPrice(){
	$(document.body).append('刷新价格<br />');
	var failFlag = false; // 刷新价格成功
	var httpUrl; // 请求url
	// 刷新价格
	httpUrl = 'http://buy.yhd.com/checkoutV3/init/init.do?cart2Checkbox=&operateFlag=&cartSuppress=&returnUrl=';
	$.ajax({
		type : 'GET',
		url : httpUrl,
		dataType : 'json',
		async : false, // 同步等待结果
		success : function(data) {
			if (data.checkoutError == null) { // 价格正确
			    $(document.body).append('价格正确,等待提交<br />');
				// 判断类型
				var products = data.productsMap;
				var i = 0;
				while (true) {
					var index = '' + i;
					if (products[index] == undefined) {
						failFlag = true;
						break;
					}else if (!products[index].gift
							&& products[index].ruleType == ruleType) {
						rdCheck = data.invoiceDTO.orderRundomString;
						totalAmount = data.paymentList.paymentAccount.cashAmountNeedToPay;//需支付的总金额
						cardAmount = data.paymentList.paymentAccount.useableCardAmount;//礼品卡可用余额
						break;
					}
					i = i + 1;
				}
			}else{
				$(document.body).append(data.checkoutError.msg);
				failFlag = true;
			}
		}
	});
	
	// 刷新价格失败，再次刷新
	if(failFlag){
		flushPriceMax--;
		if(flushPriceMax > 0){ // 未超过最大次数
			setTimeout(flushPrice, 2667);
		}
		$(document.body).append("刷不到优惠类型:"+ruleType+"的价!<br />");
		return;
	}
	
	if(payType==2 || payType==3){// 使用余额
		httpUrl = 'http://buy.yhd.com/checkoutV3/payment/sendAccountVerifyCode.do?amount='+totalAmount;
		$.ajax({
			url:httpUrl,
			type:'POST',
			success:function(data){
				if(data.accountSmsSendResult.message == '短信发送成功'){
					phoneNum = data.accountSmsSendResult.data.mobile;
					$(document.body).append('短信发送成功，延时查询验证码...<br />');
					setTimeout(getRdForBuy,timeOut);
				}else{
					$(document.body).append('短信发送失败：'+data.accountSmsSendResult.message);
				}
			}
		});
	}else{	
		submitOrder();
	}
}

function getRdForBuy(){
	chrome.extension.sendMessage({greeting:"smsCode",No:phoneNum},function(response){
        $(document.body).append('获取到的验证码：'+response.smsCode);
  		if(response.smsCode!='error'){
  			if(payType==2){
  				usingAccountPay(response.smsCode);
  			}else if(payType==3){
  				usingCardAccountPay(response.smsCode);
  			}
  		}
	});
}

function usingCardAccountPay(code){
	// 使用礼品卡支付逻辑
	if(cardAmount > 0){
		httpUrl = 'http://buy.yhd.com/checkoutV3/payment/savePaybyAccount.do?accountType=card&amount=' + cardAmount + '&vaildCode='+code;
		$.ajax({
			type : 'POST',
			url : httpUrl,
			dataType : 'json',
			async : false, // 同步等待结果
			success : function(data) {
				submitOrder();
			}
		});
	}
}

function usingAccountPay(code){
	// 使用账户余额支付逻辑
	if(totalAmount > 0){
		httpUrl = 'http://buy.yhd.com/checkoutV3/payment/savePaybyAccount.do?accountType=cash&amount='
				+ totalAmount + '&vaildCode='+code;
		$.ajax({
			type : 'POST',
			url : httpUrl,
			dataType : 'json',
			success : function(data) {
				submitOrder();
			}
		});
	}
}

// 提交订单
function submitOrder(){
	$(document.body).append('提交订单<br />');
	// 提交订单
	var httpUrl = 'http://buy.yhd.com/checkoutV3/confirm/confirmOrder.do?orderID=1&rdCheck='
			+ rdCheck + '&rd=' + Math.random() + '&needProductDetail=1';
	$.ajax({
		type : 'POST',
		url : httpUrl,
		dataType : 'json',
		async : false, // 同步等待结果
		success : function(data) {
			if(data.checkoutError == null){ // 提交成功
				window.location.href="http://my.yhd.com/order/finishOrder.do?orderCode="+data.orderCode+"#pay_shaoma_div";
			}else{
				$(document.body).append('提交失败<br />');
				flushPriceMax--;
				if(flushPriceMax > 0){ // 未超过最大次数
					$(document.body).append('正在重试<br />');
					flushPrice();
				}
			}
		}
	});
}

//加购物车
function checkAddCart(addCart){
	$(document.body).append('开始加购物车<br />');
	var httpUrl; // 请求url
	if (addCart) { // 加购物车
		if(flushPriceMax-- <= 0){
			return;
		}
		httpUrl = 'http://cart.yhd.com/cart/opt/add.do?productId=' + productId + '&rd=' + Math.random();
		$.getJSON(httpUrl, function(data){
			if (data.code != '00000000') { // 加购物车失败
				setTimeout(checkAddCart, 200);
				console.log(data.msg);
			}else{
				console.log('加购物车成功：',data.msg);
				addCart = false; // 加购物车成功不需要
				flushPrice();
			}
		});
	}else{ // 已加购物车，直接刷新价格
		flushPrice();
	}
}

function delayGetRd(){
	if(payType==1){//扫码立刻提交订单
		$(document.body).append('立刻提交<br />');
	}else{//账户支付延迟提交
		$(document.body).append('延迟提交<br />');
	}
	flushPrice();
}

//Main方法
(function(){
	if(ruleType==1){//换购
		$(document.body).append('延迟1s发送换购验证码<br />');
		setTimeout(huangou,1000);
	}else{//非换购
		if(productId && productId != ''){//加购物车
			var addCart = true;//是否需要加车标识
			console.log(productId);
			checkAddCart(addCart);
		}else{
			flushPrice();
		}
	}
})();

function huangou(){
	var url = 'http://t.yhd.com/tuangou/ajax/ajaxSmsSendForHuangou.do';
	$.ajax({
		url:url,
		type:'get',
		dataType:'json',
		success:function(data){
			if(data.code!=1){
				alert(data.msg);
			}else{//验证码发送成功
				getRd(data.data); //自动豪华
			}
		}
	});
}

/**
 * 取验证码，取成功了就换购
 * @return {[type]} [description]
 */
function getRd(phoneNum){
	chrome.extension.sendMessage({greeting:"smsCode",No:phoneNum},function(response){
		$(document.body).append('获取到了验证码：'+ response.smsCode +'<br />');
  		if(response.smsCode!='error'){
  			goHuan(response.smsCode);
  		}
	});
}
/**
 * 换购提交
 * @param  {[type]} rd [description]
 * @return {[type]}    [description]
 */
function goHuan(rd){
	$.ajax({
        type: "POST",  
        url:  "http://t.yhd.com/tuangou/seckill.do", 
        dataType:'json',
        data: {
        	orderInfoId:addrId,
        	verifyCode:12345,
        	serialId:12345,
        	verifySig:123,
			captchaToken:123,
			buyNums:1,
			invokeType:0,
			grouponId:grouponId,
			verifyCodeForHuangou:rd,
			orderCodesForHuangou:orderCodesForHuangou
        },  
        success: function(responseData){
        	if(responseData.code==1){ //普通秒杀下单成功
        		var orderCode = responseData.data;
        		var url = "http://my.yhd.com/order/finishOrder.do?orderCode="+orderCode;
        		window.location=url;
        	}else if(responseData.code==50){//排队秒杀排队成功
        		var token = responseData.data;
        		var url = "http://cart.yhd.com/cart/yqs/waiting.do?token="+token+"&returnUrl=";
        		window.location=url;
        	}else if(responseData.code==51){//排队秒杀排队不成功
        		//alert(responseData.message);
        		var url = "http://cart.yhd.com/cart/yqs/waiting.do?status=fail&code="+responseData.code;
        		window.location=url;
        	}else if(responseData.code==60){//排队秒杀,排队人数达到上限
        		//alert(responseData.message);
        		//跳到购物车
        		var url = "http://cart.yhd.com/cart/yqs/waiting.do?status=fail&code="+responseData.code;
        		window.location=url;
        	}else if(responseData.code==61){//排队秒杀,用户购买数达到上限
        		//alert(responseData.message);
        		//跳到购物车
        		var url = "http://cart.yhd.com/cart/yqs/waiting.do?status=fail&code="+responseData.code;
        		window.location=url;
        	}else{
        		$(document.body).append(responseData.message);
        	}
        }
    });
}

